package com.plpm.config;

import javax.annotation.PreDestroy;

import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.pool.SessionPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

/**
 * IoTDB Session配置类
 *
 * @author PLPM Team
 * @version 1.0
 */
@Slf4j
@Configuration
public class SessionLocalConfig {

    @Autowired
    private IoTDBConfig iotdbConfig;

    private SessionPool sessionPool;

    /**
     * 创建IoTDB Session连接池
     * 如果创建失败，将抛出异常阻止应用程序启动
     */
    @Bean
    public SessionPool sessionPool() {
        try {
            log.info("正在创建IoTDB Session连接池...");
            log.info("连接信息: {}:{}, 用户: {}, 数据库: {}",
                    iotdbConfig.getHost(), iotdbConfig.getPort(),
                    iotdbConfig.getUsername(), iotdbConfig.getDatabase());

            sessionPool = new SessionPool.Builder()
                    .host(iotdbConfig.getHost())
                    .port(iotdbConfig.getPort())
                    .user(iotdbConfig.getUsername())
                    .password(iotdbConfig.getPassword())
                    .maxSize(iotdbConfig.getSessionPoolSize())
                    .enableRedirection(true)  // 启用重定向
                    .build();

            log.info("IoTDB Session连接池创建成功，池大小: {}", iotdbConfig.getSessionPoolSize());
            return sessionPool;

        } catch (Exception e) {
            log.error("创建IoTDB Session连接池失败,IoTDB服务可能未启动", e);
            log.error("应用程序无法启动,请检查IoTDB服务是否正常运行");
            throw new RuntimeException("IoTDB Session连接池创建失败,应用程序无法启动: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建单个Session Bean（用于简单操作）
     * 如果创建失败，将抛出异常阻止应用程序启动
     */
    @Bean
    public Session iotdbSession() {
        try {
            log.info("正在创建IoTDB Session...");

            Session session = new Session.Builder()
                    .host(iotdbConfig.getHost())
                    .port(iotdbConfig.getPort())
                    .username(iotdbConfig.getUsername())
                    .password(iotdbConfig.getPassword())
                    .enableRedirection(true)  // 启用重定向
                    .build();

            session.open();
            log.info("IoTDB Session创建并连接成功");
            return session;

        } catch (Exception e) {
            log.error("创建IoTDB Session失败，IoTDB服务可能未启动", e);
            log.error("应用程序无法启动，请检查IoTDB服务是否正常运行");
            throw new RuntimeException("IoTDB Session创建失败，应用程序无法启动: " + e.getMessage(), e);
        }
    }

    /**
     * 应用关闭时清理资源
     */
    @PreDestroy
    public void destroy() {
        try {
            if (sessionPool != null) {
                sessionPool.close();
                log.info("IoTDB Session连接池已关闭");
            }
        } catch (Exception e) {
            log.error("关闭IoTDB Session连接池时发生错误", e);
        }
    }
}
